from django.core.cache import cache

from goods.models import GoodsChannelGroup


def get_categories():
    # 从cache中取数据  category_data

    data = cache.get('category_data')

    if data:
        return data

    # 获取商品分类信息
    data = {}

    # 遍历频道组

    # 取所有的频道组
    channel_group_all = GoodsChannelGroup.objects.all()
    # 构建频道组数据
    for channel_group in channel_group_all:
        channel_group_data = {"channels": [], "sub_cats": []}
        data[channel_group.id] = channel_group_data
        # 添加频道信息
        # 取所有频道
        channels = channel_group.goodschannel_set.all()
        for channel in channels:
            channel_data = {"id": channel.id, "name": channel.category.name, "url": channel.url}
            channel_group_data["channels"].append(channel_data)

            # 获取一级分类
            cat1 = channel.category

            # 遍历二级分类
            cat2_all = cat1.subs.all()
            for cat2 in cat2_all:
                cat2_data = {
                    "id": cat2.id,
                    "name": cat2.name,
                    "sub_cats": []
                }
                channel_group_data['sub_cats'].append(cat2_data)

                cat3_all = cat2.subs.all()
                # 遍历三级分类
                for cat3 in cat3_all:
                    cat3_data = {"id": cat3.id, "name": cat3.name}
                    cat2_data['sub_cats'].append(cat3_data)

    # 返回数据前, 存到cache
    cache.set('category_data', data, 3600*24)
    return data